import React, { useEffect, useState } from 'react'
import styles from './index.module.scss'
import { Button, Input, Table, Form, message, Pagination, PaginationProps } from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { set_admin_list_data } from '@/store/slice/user'
import { select_admin_list } from '@/store/slice/user/select'
import { get_admin_list_async } from '@/store/slice/user/request'
import { useAppDispatch, useAppSelector } from '@/store'
import dayjs from 'dayjs'
import FormItem from 'antd/es/form/FormItem'
import { DataType, FinishType } from './interface'
import { deleteAdmin } from '@/util/request'

// 初始PAGE_SIZE的设置
let PAGE_SIZE = 6
// 总条数的显示
const showTotal: PaginationProps['showTotal'] = total => `总共有 ${total} 位老师`
// 每页展示多少条数据
const pageSizeOptions = [6, 8, 10]
// 当前分页器的页数
let CURRENT = 1

// 管理员管理
export default function AdminManage() {
  const dispatch = useAppDispatch()
  const admin_list_data = useAppSelector(select_admin_list)

  const [messageApi, contextHolder] = message.useMessage()

  // 初始化数据 要不然如果有搜索参数，去了其他页面，再回来参数还在
  const initialData = async () => {
    CURRENT = 1
    PAGE_SIZE = 6
    const search_param = { name: '', phone: '' }
    await dispatch(set_admin_list_data({ search_param }))
    dispatch(get_admin_list_async({ pageSize: PAGE_SIZE, pageNo: 1, ...search_param }))
  }

  // 获取管理员列表
  useEffect(() => {
    initialData()
  }, [])

  // 给每一个admin添加key属性
  const data: DataType[] = admin_list_data.list.map((item: any) => {
    return {
      ...item,
      key: item._id
    }
  })

  const columns: ColumnsType<DataType> = [
    {
      title: '花名',
      key: 'name',
      dataIndex: 'name',
      render: text => <a>{text}</a>
    },
    {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone'
    },
    {
      title: '微信',
      dataIndex: 'vChat',
      key: 'vChat'
    },
    {
      title: '技术栈',
      dataIndex: 'techStack',
      key: 'techStack'
    },
    {
      title: '注册时间',
      dataIndex: 'created',
      key: 'created',
      render: (_, record) => {
        return <>{dayjs(_).format('YYYY-MM-DD HH:mm:ss')}</>
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button type="primary" danger onClick={() => handleDelete(record._id)}>
          删除
        </Button>
      )
    }
  ]

  // 删除老师
  const handleDelete = async (id: number) => {
    const res: any = await deleteAdmin(id)
    if (res.data.code == 200) {
      messageApi.open({
        type: 'success',
        content: '删除老师成功'
      })

      dispatch(
        get_admin_list_async({
          pageNo: 1,
          pageSize: PAGE_SIZE,
          ...admin_list_data.search_param
        })
      )
    } else {
      messageApi.open({
        type: 'error',
        content: '删除老师失败'
      })
    }
  }

  // 优化搜素参数
  const transformSearch = (value: FinishType) => {
    if (typeof value.name === 'undefined') {
      value.name = ''
    }

    if (typeof value.phone === 'undefined') {
      value.phone = ''
    }

    return value
  }

  // 点击查询按钮
  async function onFinish(values: FinishType) {
    const search_param = transformSearch(values)

    // 修改仓库中的查询参数
    dispatch(set_admin_list_data({ search_param }))

    // 进行按需查询
    dispatch(
      get_admin_list_async({
        pageNo: 1,
        pageSize: PAGE_SIZE,
        ...search_param
      })
    )
  }

  // 分页器改变
  const changePage = (updatePageNo: number, update_pageSize: number) => {
    CURRENT = updatePageNo
    PAGE_SIZE = update_pageSize
    dispatch(
      get_admin_list_async({
        pageNo: updatePageNo,
        pageSize: update_pageSize,
        ...admin_list_data.search_param
      })
    )
  }

  return (
    <div>
      {contextHolder}
      <div className={styles.search}>
        <Form onFinish={onFinish} layout="inline">
          <Form.Item label="花名:" name="name">
            <Input />
          </Form.Item>

          <Form.Item label="手机号" name="phone">
            <Input />
          </Form.Item>

          <FormItem>
            <Button style={{ marginLeft: 20 }} htmlType="submit" type="primary">
              查询
            </Button>
          </FormItem>
        </Form>
      </div>
      <div className={styles.table}>
        <Table columns={columns} dataSource={data} pagination={false} />
        <Pagination pageSize={PAGE_SIZE} onChange={changePage} current={CURRENT} total={admin_list_data.count} pageSizeOptions={pageSizeOptions} showTotal={showTotal} showSizeChanger style={{ marginTop: 20 }} />
      </div>
    </div>
  )
}
